//引入express模块
const express = require("express");
//引入数据库连接模块
const pool = require("../pool.js");
//引入公用函数
const xsp_fn = require("../others/xsp_fn");
//创建路由器对象
const mR = express.Router();
//以下为接口部分

//购物车添加接口
//接口地址：http://127.0.0.1:3000/cart/add
//接口方式：post
mR.post("/add", (req, res, next) => {
  let c_add = xsp_fn.api_add("user_cart");
  pool.query(c_add.sql, [req.body], (err, data) => {
    if (err) {
      res.send(c_add.err);
      next(err);
    } else {
      console.log(data);
      res.send(c_add.success);
    }
  });
});

//删除购物车接口
//接口地址：http://127.0.0.1:3000/cart/delete
//接口方式：delete
mR.get("/delete", (req, res, next) => {
  let c_delete = `delete from user_cart where cart_id=?`;
  pool.query(c_delete, [req.query.cart_id], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.changedRows) {
      res.send({ code: 0, msg: "删除失败" });
    } else {
      res.send({ code: 1, msg: "删除成功" });
    }
  });
});

//修改购物车接口
//接口地址：http://127.0.0.1:3000/cart/update
//接口方式：put
mR.put("/update", (req, res, next) => {
  let ss = req.body.appraise_id;
  console.log(ss);
  let c_update = `update user_cart set ? where cart_id=?`;
  pool.query(c_update, [req.body, req.body.cart_id], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.changedRows) {
      res.send({ code: 1, msg: "修改成功" });
    } else {
      res.send({ code: 0, msg: "修改失败" });
    }
  });
});

//查看用户购物车信息
//接口地址：http://127.0.0.1:3000/cart/userinfo
//接口方式：get
mR.get("/userinfo", (req, res, next) => {
  // console.log(req.query.uid);
  pool.query(
    "select * from user_cart where user_id=?",
    [req.query.user_id],
    (err, data) => {
      if (err) {
        console.log(err);
        next(err);
        return;
      }
      res.send({ code: 1, msg: "查询成功", data });
    }
  );
});

//查看用户购物车商品信息信息
//接口地址：http://127.0.0.1:3000/cart/qqq
//接口方式：get
mR.get("/qqq", (req, res, next) => {
  pool.query(
    `select * from goods_info where goods_id=?`,
    [req.query.goods_id],
    (err, data) => {
      if (err) {
        console.log(err);
        next(err);
        return;
      }
      console.log(data[0]);
      res.send({ code: 1, msg: "查询成功", data });
    }
  );
});

//暴露出去
module.exports = mR;
